package com.runfast.waimai.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.ui.ModelMap;

import java.text.SimpleDateFormat;
import java.util.*;

public class SingleSendSms {
    private final static String APP_KEY = "23476026"; //AppKey从控制台获取
    private final static String APP_SECRET = "53aabb325c6b2dc70803cda1d0410cdb"; //AppSecret从控制台获取
    private final static String SIGN_NAME = "跑腿快车"; // 签名名称从控制台获取，必须是审核通过的
//    private final static String TEMPLATE_CODE = "SMS_17020084"; //模板CODE从控制台获取，必须是审核通过的
    private final static String HOST = "sms.market.alicloudapi.com"; //API域名从控制台获取

    private final static String appcode = "70118048691549cabc7c31a719c85b5a";

    private final static String ERRORKEY = "errorMessage";  //返回错误的key
//    private final static Logger log = Logger.getLogger("alisms");

    // @phoneNum: 目标手机号，多个手机号可以逗号分隔;
    // @params: 短信模板中的变量，数字必须转换为字符串，如短信模板中变量为${no}",则参数params的值为{"no":"123456"}
    /*public static String sendMsg(String phoneNum, String params,String template_code){
        String path = "/singleSendSms";
        if(true)
        {
        	  //return "  ";
        }
        System.out.println("----------come send--------");
        String responseBody = "";
        Request request =  new Request(Method.GET, HttpSchema.HTTP + HOST, path, APP_KEY, APP_SECRET, Constants.DEFAULT_TIMEOUT);

        //请求的query
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("SignName", SIGN_NAME);
        querys.put("TemplateCode", template_code);
        querys.put("RecNum", phoneNum);
        querys.put("ParamString", params);
        request.setQuerys(querys);

        try {
            Map<String, String> bodymap = new HashMap<String, String>();
            Response response = Client.execute(request);
          //根据实际业务需要，调整对response的处理
            if (null == response) {
                System.out.println("no response");
                responseBody = "no response";
            } else if (200 != response.getStatusCode()) {
            	System.out.println("response");
            	StringBuilder sb = new StringBuilder("StatusCode:");
            	sb.append(response.getStatusCode()).append("\n").append("ErrorMessage:"+response.getErrorMessage())
            	.append("\n").append("RequestId:"+response.getRequestId());
                responseBody = sb.toString();
            } else {
            	System.out.println("game over");
            	responseBody = response.getBody();
                bodymap = ReadResponseBodyContent(response.getBody());
                if (null != bodymap.get(ERRORKEY)) {
                  //当传入的参数不合法时，返回有错误说明
                    System.out.println(bodymap.get(ERRORKEY));
                } else {
                       //成功返回map，对应的key分别为：message、success等
                    //System.out.println(bodymap);
                	System.out.println("game over23");
                }
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            responseBody = e.getMessage();
        }
//        log.info(responseBody);
        return responseBody;
    }*/

    /*public static ModelMap sendMsg(String phoneNum, String params, String template_code){

        ModelMap modelMap = new ModelMap();
        String path = "/singleSendSms";
        String method = "GET";

        Map<String, String> headers = new HashMap<String, String>();
       //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("SignName", SIGN_NAME);
        querys.put("TemplateCode", template_code);
        querys.put("RecNum", phoneNum);
        querys.put("ParamString", params);


        try {
            *//**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             *  相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             *//*
            HttpResponse response = HttpUtils.doGet(HttpSchema.HTTP + HOST, path, method, headers, querys);
            String toString = EntityUtils.toString(response.getEntity());
            System.out.println("=============短信请求参数"+params+"==================");
            System.out.println("=============短信返回结果"+toString+"==================");
            JSONObject jsonObject = new JSONObject(toString);
            Object success = jsonObject.get("success");
            modelMap.put("success",success);
            Object message = null;
            if(success.equals("false")){
                message = jsonObject.get("message");
            }


            modelMap.put("message",message);
            return modelMap;
            ///获取response的body

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/

    public static ModelMap sendMsg(String phoneNum, String params, String template_code) {

        ModelMap modelMap = new ModelMap();
        BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
                        .build(),
                null,
                null,
                null
        );
        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();

        String url = "http://api.zthysms.com/sendSms.do";
        HttpPost httpPost = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);

        ArrayList<NameValuePair> postParams = new ArrayList<>();
        postParams.add(new BasicNameValuePair("username", "ptkc888hy"));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String formatDate = dateFormat.format(new Date());
        postParams.add(new BasicNameValuePair("tkey", formatDate));

        String password = "nbujTx";

        postParams.add(new BasicNameValuePair("password", DigestUtils.md5Hex(DigestUtils.md5Hex(password).toString().toLowerCase()+formatDate).toString().toLowerCase()));
        postParams.add(new BasicNameValuePair("mobile", phoneNum));

        try {
//            ObjectMapper objectMapper = new ObjectMapper();
//            Map paramsMap = objectMapper.readValue(params, Map.class);
            JSONObject paramsMap = new JSONObject(params);
            Object code = paramsMap.get("code");

            String template = "【跑腿快车】你的验证码为：${code}，有效时间为5分钟，请尽快使用。";
            if("SMS_17020084".equals(template_code)){
                template = "【跑腿快车】你的验证码为：${code}，有效时间为5分钟，请尽快使用。";
                template = template.replace("${code}",code.toString());
            }else if("SMS_47920224".equals(template_code)){
                template = "【跑腿快车】你的验证码为：${code}，有效时间为5分钟，请尽快使用。";
                template = template.replace("${passwd}",code.toString());
            }
            postParams.add(new BasicNameValuePair("content", template));

            UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(postParams,"utf-8");
//            httpPost.addHeader("Content-Type", "text/plain");
            httpPost.setEntity(postEntity);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            String s = EntityUtils.toString(httpEntity, "UTF-8");
            System.out.println("=============短信请求参数："+params+"==================");
            System.out.println("=============短信返回结果："+s+"==================");
            if(s.startsWith("1,")){
                modelMap.put("success",true);
                modelMap.put("message","短信发送成功");
                return modelMap;
            }else{
                modelMap.put("success",false);
                modelMap.put("message","s");
                return modelMap;
            }
        }catch (Exception e){

            e.printStackTrace();;
            modelMap.put("success",false);
            modelMap.put("message",e.getMessage());
        }

        return modelMap;
    }

    private static Map<String, String> ReadResponseBodyContent(String body) {
        Map<String, String> map = new HashMap<String, String>();    
        //System.out.println(body);
        try {

            JSONObject jsonObject = new JSONObject(body);
            if (null != jsonObject) {    
            	Iterator<String> it = jsonObject.keys();
            	while(it.hasNext()){
            		String key = it.next();
            		map.put(key, jsonObject.optString(key));
            	}             
            }
            if ("false".equals(map.get("success"))) {
                map.put(ERRORKEY, map.get("message"));
            }
        } catch (Exception e) {
            map.put(ERRORKEY, body);
        }
        return map;
    }
//
//
//    public  static void main(String agrs[]){
//        SingleSendSms app = new SingleSendSms();
//        app.sendMsg("13471024510","{'code':'123321'}","SMS_17020084");
//    }
}
